public class LCS1 {
    // 最长公共子串
    // https://www.nowcoder.com/practice/f33f5adc55f444baa0e0ca87ad8a6aac?tpId=295&tags=&title=&difficulty=0&judgeStatus=0&rp=0&sourceUrl=%2Fexam%2Foj%3Fpage%3D1%26tab%3DSQL%25E7%25AF%2587%26topicId%3D295
    public String LCS (String str1, String str2) {
        // write code here
        // dp[i][j]表示以str1第i个位置为结尾的字符串和str2以j位置为结尾的最长公共子串
        str1 = " " + str1;
        str2 = " " + str2;
        int len1 = str1.length();
        int len2 = str2.length();
        String[][] dp = new String[len1][len2];
        for (int i = 0; i < len1; i++) {
            dp[i][0] = "";
        }
        for (int j = 1; j < len2; j++) {
            dp[0][j] = "";
        }
        // 因为最长的公共子串不一定是以两个字符串的最后一个字符结尾，
        // 所以就需要使用额外的变量在遍历的过程中记录最长的公共子串
        int maxLength = 0;
        String ret = "";
        for (int i = 1; i < len1; i++) {
            for (int j = 1; j < len2; j++) {
                if (str1.charAt(i) == str2.charAt(j)) {
                    if (str1.charAt(i - 1) == str2.charAt(j - 1)) {
                        dp[i][j] = dp[i - 1][j - 1] + str1.charAt(i);
                    } else {
                        dp[i][j] = "" + str1.charAt(i);
                    }
                } else {
                    dp[i][j] = dp[i - 1][j].length() > dp[i][j - 1].length()
                            ? dp[i - 1][j] : dp[i][j - 1];
                }
                if (dp[i][j].length() > maxLength) {
                    maxLength = dp[i][j].length();
                    ret = dp[i][j];
                }
            }
        }
        return ret;
    }

    public static void main(String[] args) {
        LCS1 lcs1 = new LCS1();
        String str1 = "1AB2345CD";
        String str2 = "12345EF";
        System.out.println(lcs1.LCS(str1, str2));
    }
}
